/* Create tree layout */

#include <algorithm>

#include <memchart/types.hpp>

#include "chart_box.hpp"

#include "memory_chart.hpp"

namespace memchart
{
	using std::max;

	pair<int, int> MemoryChart::tree_align (chart_box & box, int left, int top)
	{
		int width = 0, max_height = 0;
		int reltop = box.widget->get_height() + vspacing;

		for (edge_iter e = box.edges.begin(); e != box.edges.end(); ++e)
		{
			box_iter v = boxes.find(*e);
			if (v != boxes.end())
			{
				pair<int, int> dim = tree_align(v->second,
					left + width, top + reltop);
				max_height = max(max_height, dim.second);
				width += dim.first + hspacing;
			}
		}
		if (width > 0)
			width -= hspacing;
		width = max(width, box.widget->get_width());
		if (max_height == 0)
			reltop -= vspacing;

		move(*box.widget, left + (width - box.widget->get_width()) / 2, top);

		return make_pair(width, max_height + reltop);
	}

	void MemoryChart::layout_tree ()
	{
		pair<int, int> dim = tree_align(torder[0]->second, 0, 0);

		set_size_request(dim.first, dim.second);
	}
}
